import axios from "axios";
const toolClass = {
  // 格式化element 日期选择器时间=>2022-12-20
  formatDateTime(time) {
    let date = new Date(time);
    let y = date.getFullYear();
    let m = date.getMonth() + 1;
    m = m < 10 ? "0" + m : m;
    let d = date.getDate();
    d = d < 10 ? "0" + d : d;
    let h = date.getHours();
    h = h < 10 ? "0" + h : h;
    let minute = date.getMinutes();
    let second = date.getSeconds();
    minute = minute < 10 ? "0" + minute : minute;
    second = second < 10 ? "0" + second : second;
    return y + "-" + m + "-" + d + " " + h + ":" + minute + ":" + second;
  },
  // 深拷贝
  deepClone(data) {
    return JSON.parse(JSON.stringify(data));
  },
  // 对象数组[{key:"name",value:"gz"}]->对象{"name":"gz"}
  arrayToObj(data) {
    let obj = {};
    if (data && data.length > 0) {
      for (let i = 0; i < data.length; i++) {
        let item = data[i];
        for (const key in item) {
          obj[item.key] = item.value;
        }
      }
    } else {
      obj = "";
    }
    return obj;
  },
  // { name: 1, age: 2 }=>[{key:"name",value:"1"},{key:"age",value:"2"}]
  objToArray(data) {
    data = Object.keys(data).length > 0 ? JSON.parse(data) : {}
    let array = [];
    if (data && Object.keys(data).length > 0) {
      for (const key in data) {
        array.push({ key: key, value: data[key] });
      }
    }
    return array;
  },
  // 原生axios post
  axiosPost(url, data, timeout = 0) {
    return new Promise((resolve, reject) => {
      axios
        .post(url, data, { timeout: timeout * 1000 })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  },
  // 原生axios get
  axiosGet(url, data, timeout = 0) {
    return new Promise((resolve, reject) => {
      axios
        .get(url, { params: data }, { timeout: timeout * 1000 })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject(err);
        });
    });
  }
};

export default toolClass;
